package shopping.service.impl;

import shopping.bean.*;
import shopping.dao.ClothesDao;
import shopping.dao.OrderDao;
import shopping.dao.OrderItemDao;
import shopping.dao.impl.ClothesDaoImp;
import shopping.dao.impl.OrderDaoImpl;
import shopping.dao.impl.OrderItemDaoImpl;
import shopping.service.OrderService;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private ClothesDao clothesDao = new ClothesDaoImp();

    @Override
    public String createOrder(List list, Integer userId,Integer status) {
        // 订单号===唯一性
        String orderId = System.currentTimeMillis()+""+userId;
        // 创建一个订单对象
        Order order = new Order(orderId,new Date(),list.getTotalPrice(), status,userId);
        // 保存订单
        orderDao.saveOrder(order);

//        int a = 10/0; // by zero
        // 遍历购物车中每一个商品项转换成为订单项保存到数据库
        for (Map.Entry<Integer, ListItem>entry : list.getItems().entrySet()){
            // 获取每一个购物车中的商品项
            ListItem listItem = entry.getValue();
            // 转换为每一个订单项
            OrderItem orderItem = new OrderItem(null,listItem.getName(),listItem.getCount(),listItem.getPrice(),listItem.getTotalPrice(), orderId);
            // 保存订单项到数据库
            orderItemDao.saveOrderItem(orderItem);
            Clothes clothes = null;
            // 更新库存和销量
            if (status == 0){
                clothes = clothesDao.queryClothesById(listItem.getId());
                clothes.setSales( clothes.getSales() + listItem.getCount() );
                clothes.setStock( clothes.getStock() - listItem.getCount() );
            }else{
                //此处不能用id查询，因为新添加的服装信息的id是自增生成的，有可能找不到
                clothes = clothesDao.queryClothesByName(listItem.getName()); //
//                clothes.setSales( clothes.getSales() + listItem.getCount() );
                clothes.setStock( clothes.getStock() + listItem.getCount() );
            }

            clothesDao.updateClothes(clothes);

        }
        // 清空购物车
        list.clear();

        return orderId;
    }

    @Override
    public ArrayList selectOrderAll() {

        ArrayList<Order> orderList = orderDao.selectOrderAll();
        return orderList;
    }

    @Override
    public ArrayList<OrderItem> selectOrderItemByOrder_id(String orderId) {
        ArrayList<OrderItem> orderList = orderDao.selectOrderItemByOrder_id(orderId);

        return orderList;
    }
}
